package com.itstyle.seckill.topic.jvm;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Auther: liuwenxiang
 * @Date: 2020/3/20 00:23
 * @Description:
 */
public class Fanshe {


    public double d;

    public String f="lwx";


    public Fanshe(){ }

    public Fanshe(int a, int b){
        System.out.println("a="+a+"b="+b);
    }


    public int add(int a, int b){
        return a + b;
    }


    public static void main(String[] args) {

        //Constructor();
        //Field();
        Method();
    }


    /**
     * 通过反射，
     * 获取对象的构造器
     * 通过构造器创建对象,并调用对象方法
     */
    public static void Constructor(){
        try {
            Class cls = Class.forName("Fanshe");
            Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Constructor ct=  cls.getConstructor(partypes);//通过class对象获取构造器对象
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj = ct.newInstance(arglist);//通过构造器对象创建实例对象
            System.out.println(retobj);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过反射：获取Class对象,然后通过Class对象创建实例对象
     * 通过实例对象获取对象属性
     */
    public static void Field(){
        Class cls = Fanshe.class;
        try {
            Object o = cls.newInstance();
            Field[] fields = cls.getFields();
            for (int i=0;i<fields.length;i++){
                Field field = fields[i];
                System.out.println(field.get(o));//获取对象属性
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    public static void Method(){
        try {
            Class cls = Class.forName("com.itstyle.seckill.topic.jvm.Fanshe");
            Method method1 = cls.getMethod("add",Integer.TYPE,Integer.TYPE);//获取"方法"
            method1.invoke(cls.newInstance(),4,6);//执行方法
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
